var docTypeArray = ["clinic","protomedicus","physician","resident"] ;
var titleMrQuality  = {
    "hosp":{"desc":"全院"},
    "dep":{"desc":"科室"},
    "ward":{"desc":"病区"},
    "doctor":{"desc":"医师"},
    "protomedicus":{"desc":"主任医师"},
    "clinic":{"desc":"主诊医师"},
    "resident":{"desc":"住院医师"},
    "physician":{"desc":"主治医师"},
}

$(function(){
	showCondition(true, 0, 0, 1,[]);//加载查询条件
    paramTabPage[tabId].dateType = "outDate" ;
    // 没有检测类型，则默认全院
    if(paramTabPage[tabId].monitorType == undefined) {
        paramTabPage[tabId].monitorType = "hosp" ;
    }

    //轮播插件初始化
    initializeCarousel();
	// 整体统计
    overviewMRCount() ;
    overviewItemCount() ;
    // 查询得分情况
    findFullScore() ;
    // 违规项目
    var param = drgUI.setAjaxData(tabId) ;
    var nextMonitorType = getNextMonitortype(param.monitorType) ;
    // 违规项的加载
    drawViolationItems({"monitorType":nextMonitorType==null?param.monitorType:nextMonitorType},$("#"+tabId+" #violationItemsTable"),$("#"+tabId+" #violationItemsEchart")) ;
    // alert(param.monitorType+" -> "+nextMonitorType)
    // 违规科室或医师的div
    var id="violateMRQ" ;
    // 违规医师
    if(nextMonitorType==null && isDoctorMonitorType(param.monitorType)) { // 不显示违规科室或医师
        $("#"+tabId+" #violateMRQ").remove() ;
    } else if (nextMonitorType=="doctor"){  // 违规医师
        // 医师分页签显示
        $("#"+tabId +" #"+id+" .infocq").append("<div class=\"tab-content\"></div>") ;
        drawViolationDoctor(id) ;
    } else {
        var str = "<div class=\"row-fluid clearfix\">" +
            "<div id=\"violationDepsEchart\" class=\"col-md-6 margintop10\" style=\"height:320px;\"></div>" +
            "<div class=\"col-md-6 margintop10\">" +
            "<table id=\"violationDepsTable\" class=\"display\" width=\"100%\" style=\"white-space:nowrap\"></table>" +
            "</div>" +
            "</div>" ;
        $("#"+tabId +" #"+id+" .infocq").append(str) ;
        drawViolationDeps({"monitorType":nextMonitorType},$("#"+tabId+" #violationDepsTable"),$("#"+tabId+" #violationDepsEchart"));
    }
    //当 AJAX 请求完成时，jQuery 会检查是否存在更多的 AJAX 请求。如果没有其他请求正在等待运行，ajaxStop()方法会运行指定的函数。
	$(document).ajaxStop(function(){
		drgUI.tips();//title 信息提示框
	});
})

/**
 * @Description: 轮播插件初始化
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/20 8:44 
 */
function initializeCarousel() {
    var owl = $('.owl-carousel'); // save reference to variable
    owl.owlCarousel({
        items:6 ,
        loop:true,
        nav:true,
        // margin:10,
        autoplay:true,
        //autoplayTimeout:1000,
        autoplayHoverPause:true,
        dots:false
    });
}


/**
 * @Description: 医师违规统计
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/15 11:41 
 */
function drawViolationDoctor(id,dialog,condition) {
    var param = drgUI.setAjaxData(tabId) ;
    var doctors = doctorSetConfig;//全局变量里取
    // 移除原来的div
    for(var i = 0; i<doctors.length ; i++) {
        // 未配置则跳过
        if(doctors[i] == "0"){
            continue ;
        }
        var docType = "" ;
        switch (i) {
            case 0 : docType = "protomedicus" ; break ; // 主任医师
            case 1 : docType = "clinic" ; break ; // 主诊医师
            case 2 : docType = "resident" ; break ; // 住院医师
            case 3 : docType = "physician" ; break ; // 主治医师
        }
        var strli = '' ;
        var strdiv = '' ;
        if(i == 0) {
            strli+='<li role="presentation" class="active"><a href="#'+docType+"_"+id+'" role="tab" data-toggle="tab">'+ titleMrQuality[docType].desc+'</a></li>' ;
            strdiv+='<div id="'+docType+"_"+id+'" role="tabpanel" class="tab-pane active" ><div class="row-fluid clearfix"><div id="violation'+docType+'Echart" class="col-md-6 margintop10" style="height:300px;"></div>' +
                '                        <div class="col-md-6 margintop10">' +
                '                            <table id="violation'+docType+'Table" class="display" width="100%" style="white-space:nowrap"></table>' +
                '                        </div></div></div>';
        } else {
            strli+='<li role="presentation"><a href="#'+docType+"_"+id+'" role="tab" data-toggle="tab">'+titleMrQuality[docType].desc+'</a></li>' ;
            strdiv+='<div id="'+docType+"_"+id+'" role="tabpanel" class="tab-pane" ><div class="row-fluid clearfix"><div id="violation'+docType+'Echart" class="col-md-6 margintop10" style="height:300px;"></div>' +
                '                        <div class="col-md-6 margintop10">' +
                '                            <table id="violation'+docType+'Table" class="display" width="100%" style="white-space:nowrap"></table>' +
                '                        </div></div></div>';
        }
        // 窗口打开
        if (dialog instanceof jQuery ) {
            dialog.find("#"+id+" > div:nth-child(1) > ul").append(strli)
            dialog.find("#"+id+" > div:nth-child(1) > div.tab-content").append(strdiv) ;
            // 加载医师数据
            var param = {} ;
            _.extendOwn(param,condition)
            param.monitorType = docType ;
            drawViolationDeps(param,dialog.find("#violation"+docType+"Table"),dialog.find("#violation"+docType+"Echart")) ;
        } else { // 页签打开
            $("#"+tabId +" #"+id+" > div:nth-child(1) > ul").append(strli)
            $("#"+tabId +" #"+id+" > div:nth-child(1) > div.tab-content").append(strdiv) ;
            // 加载医师数据
            drawViolationDeps({"monitorType":docType},$("#"+tabId+" #violation"+docType+"Table"),$("#"+tabId+" #violation"+docType+"Echart")) ;
        }
    }
}

/**
 * @Description: 获取下一个层级
 * @param
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/12 21:23 
 */
function getNextMonitortype(currentMonitortype) {
    var monitorType = null ;
    switch(currentMonitortype){
        case "hosp":
            if(commonLayerConfig[1]=="1"){
                monitorType = "dep" ;
            }else if(commonLayerConfig[2]=="1"){
                monitorType = "ward" ;
            }
            break;
        case "dep":
            if(commonLayerConfig[2]=="1"){
                monitorType = "ward" ;
            }else if(commonLayerConfig[3]=="1"){
                monitorType = "doctor" ;
            }
            break;
        case "ward":
            if(commonLayerConfig[3]=="1"){
                monitorType = "doctor" ;
            }
            break;
        default:
            monitorType == null ;
            break;
    }

    return monitorType ;
}

/**
 * @Description: 获取条件属性
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/14 12:52
 */
function  findConditionalAttributeByMonitorType(currentMonitortype) {
    var conditionalAttribute = "" ;
    switch(currentMonitortype){
        case "dep":
            conditionalAttribute = "pardepCode" ;
            break;
        case "ward":
            conditionalAttribute = "wardCode" ;
            break;
        case "clinic":
            conditionalAttribute = "groupCode" ;
            break;
        case "protomedicus":
            conditionalAttribute = "groupCode" ;
            break;
        case "physician":
            conditionalAttribute = "groupCode" ;
            break;
        case "resident":
            conditionalAttribute = "groupCode" ;
            break;
    }
    return conditionalAttribute ;
}

/**
 * @Description:
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/6 17:10
 */
function overviewMRCount() {
    var param = drgUI.setAjaxData(tabId) ;
    // 修改标题 titleSum
    $("#"+tabId+" .titleSum").text(titleMrQuality[param.monitorType].desc+"概况")
    ajaxMr("medicalRecordQuality/overviewMRCount",param,function (result) {
        if(result.data == undefined ){
            return ;
        }
        var result = result.data[0] ;
        var valueMap = {} ;
        // 首页完整率
        valueMap.completeRatio = formatNumber(division(result.completeCount,result.totalMedicalRecord)*100,2)  ;
        valueMap.completeRatioF = formatNumMr(result.completeCount,"0")+"/"+result.totalMedicalRecord ;
        // 合格率
        valueMap.qualifiedRatio = formatNumber(division(result.qualifiedCount,result.totalMedicalRecord)*100,2) ;
        valueMap.qualifiedRatioF = formatNumMr(result.qualifiedCount,"0")+"/"+ formatNumMr(result.totalMedicalRecord,"0") ;
        // 优秀率
        valueMap.goodRatio = formatNumber(division(result.goodCount,result.totalMedicalRecord)*100,2) ;
        valueMap.goodRatioF = formatNumMr(result.goodCount,"0")+"/"+ formatNumMr(result.totalMedicalRecord,"0") ;
        // 等级评定
        var levelDesc = "" ;
        var level = 0 ;
        if(valueMap.qualifiedRatio >= 97) {
            level=4 ;
            levelDesc = "优" ;
        } else if(valueMap.qualifiedRatio >= 90 && valueMap.qualifiedRatio < 97 ) {
            levelDesc = "良" ;
            level=3 ;
        } else if(valueMap.qualifiedRatio >= 75 && valueMap.qualifiedRatio < 90) {
            levelDesc = "中" ;
            level=2 ;
        } else if(valueMap.qualifiedRatio < 75) {
            levelDesc = "差" ;
            level=1 ;
        }

        $("#"+tabId+" #ratingLevel span").remove() ;
        $("#"+tabId+" #ratingLevelDesc").text(levelDesc) ;
        for(i=1 ; i<5; i++){
            if(i<=level) {
                $("#"+tabId+" #ratingLevel").append("<span class=\"icon\" style=\"color: #E2C608\"></span>")
            } else {
                $("#"+tabId+" #ratingLevel").append("<span class=\"icon\"></span>")
            }
        }
        // 首页质量平均得分
        valueMap.avgScore = formatNumMr(result.avgScore,"0") ;
        for(var key in valueMap){
            $("#"+tabId+" span[value='"+key+"']").html(valueMap[key]) ;
        }

    }) ;
}

/**
 * @Description: 统计违规项信息
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 22:42 
 */
function overviewItemCount() {
    var param = drgUI.setAjaxData(tabId) ;
    ajaxMr("medicalRecordQuality/overviewItemCount",param,function (result) {
        if(result.data == undefined ){
            return ;
        }
        var result = result.data[0] ;
        var valueMap = {} ;
        // 首页必填项完整率
        valueMap.requiredRatio = formatNumber(division(result.requiredCount-result.violateRequiredCount,result.requiredCount)*100,2);
        valueMap.requiredRatioF = formatNumMr(result.requiredCount-result.violateRequiredCount,"0")+"/"+formatNumMr(result.requiredCount,"0") ;

        // A类错误病例数
        valueMap.violateACaseCount = result.violateACaseCount ;
        // A类扣分项目占比
        valueMap.violateARatio = formatNumber(division(result.violateACount,result.itemsCnt)*100,2) ;
        valueMap.violateARatioF = formatNumMr(result.violateACount,"0")+"/"+ formatNumMr(result.itemsCnt,"0")  ;
        for(var key in valueMap){
            $("#"+tabId+" span[value='"+key+"']").html(valueMap[key]) ;
        }
    })
}

/**
 * @Description:
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 11:38 
 */
function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}

/**
 * @Description: 获取满分方法
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/9 15:33 
 */
function findFullScore() {
    $.post(contextPath+"/medicalRecordQuality/initializeFullScore.dhc",{}).done(function(result){
        var fullScore = result.data
        if(result == null && result.data == undefined) {
            return ;
        }
        queryScore(fullScore) ;
    })
}

/**
 * @Description: 统计病案得分
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/7 21:48
 */
function queryScore(fullScore) {
    var param = drgUI.setAjaxData(tabId) ;
    // fullScore = {totalScore: {DT: 50, COST: 6, BASICINFO: 18, IP: 26}, partScore: {BASICINFO_D: 4,COST_D: 2, IP_B: 10, DT_C: 3},
    //  partClass: {A: "A类", B: "B类", C: "C类", D: "D类"},wholeClass: {DT: "诊疗信息", COST: "费用信息", BASICINFO: "患者基本信息", IP: "住院过程信息"} };
    if(fullScore.totalScore && fullScore.partScore && fullScore.wholeClass && fullScore.partClass){
    	//大类满分 {DT: 50, COST: 6, BASICINFO: 18, IP: 26}
    	var totalFullScore = fullScore.totalScore ;
    	//分类满分如 {BASICINFO@@D: 4,COST@@D: 2, IP@@B: 10, DT@@C: 3}
    	var partFullScore = fullScore.partScore ;
    	//大类信息{DT: "诊疗信息", COST: "费用信息", BASICINFO: "患者基本信息", IP: "住院过程信息"}
    	var totalClass = fullScore.wholeClass ;
    	//分类信息如 {A: "A类", B: "B类", C: "C类", D: "D类"}
    	var partClass = fullScore.partClass ;  
        $.post(contextPath+"/medicalRecordQuality/queryScore.dhc",param).done(function(result){
            if(result.data == undefined ){
                return ;
            }
            //result.data = [{SCORE_CODE: "BASICINFO", WEIGHT_CODE: "A", SCORE: 8},{SCORE_CODE: "COST", WEIGHT_CODE: "A", SCORE: 4}]
            var scoreData = result.data ;
            var dataMap = {},partScore = {} ;
    //        var dataMap = {"ip":{"ddesc":"住院过程"},"baseInfo":{"ddesc":"基本信息"},"dt":{"ddesc":"诊疗信息"},"cost":{"ddesc":"费用信息"}} ;
    //        var weight= ["A","B","C","D"] ;
            if(!isEmptyObject(scoreData)) {
                try {
                	
                    for(var o in totalClass){ 
                    	var tt = {};
                    	//名称
                    	tt["ddesc"] = totalClass[o];
                    	//满分
                    	tt["fullScore"] = formatNumber(totalFullScore[o] ,2);
                    	var partGetScore = 0;
                    	var pt = {};
                    	for(var s in scoreData){
                    		var sd = scoreData[s];
                    		if( o == sd["SCORE_CODE"] ){
                    			partGetScore += sd["SCORE"] ;
                    			pt[sd["WEIGHT_CODE"]] = sd["SCORE"];
                    		}
                    	}
                    	//得分
                    	tt["score"] = formatNumber(partGetScore ,2);
                    	//扣分
                    	tt["minusScore"] = formatNumber(totalFullScore[o] - partGetScore ,2) ;
                    	dataMap[o] = tt;
                    	partScore[o] = pt;
                    }
                    // 数据分类
                    for (var ot in dataMap) {
                        for(var pc in partClass){
                        	// 不同权重类别满分
                            dataMap[ot]["fullScore" + pc] = partFullScore[ot+"@@"+pc] ? formatNumber(partFullScore[ot+"@@"+pc] ,2)  : 0 ;
                            // 不同权重类别分数
                            dataMap[ot]["score" + pc] =  partScore[ot][pc] ? formatNumber(partScore[ot][pc] ,2) : 0 ;            
                            // 扣分
                            dataMap[ot]["minusScore" + pc] = formatNumber( dataMap[ot]["fullScore" + pc] - dataMap[ot]["score" + pc] ) ;
                        }
                    }                 
                } catch (e) {
                    console.error(e)
                }
            }

            // echart图数据
            var echartData = [] ;
            var tableData = [] ;
            for (var o in dataMap) {
                echartData.push({"ddesc":dataMap[o].ddesc,"score":dataMap[o].score,"minusScore":dataMap[o].minusScore}) ;
                tableData.push(dataMap[o]) ;
            }
            var itemStyle={"normal": {barBorderColor:'#50a1d4',barBorderWidth :2},"emphasis":{barBorderColor:'#58B1E9',barBorderWidth :2}};
            var surplusItemStyle={"normal": {barBorderColor:'#f07043',barBorderWidth :2},"emphasis":{barBorderColor:'#f5893f',barBorderWidth :2}};
            var barColor=["#50a1d4","#f07043","#7bd9a5"];
            var lines = [{"code":'score',"desc": '得分', "data":[],itemStyle:itemStyle},
                {"code":'minusScore',"desc":'扣分', "data":[],itemStyle:surplusItemStyle}];
            var formatterFunc=function(value){
                var tips='';
                if(value!=undefined && value.length>0){
                    //得分
                    tips+=value[0].seriesName+":"+value[0].value+ '</br>';
                    //扣分
                    tips+=value[1].seriesName+":"+value[1].value+ '</br>';
                    //满分
                    tips+="满分:"+formatNumber(parseFloat(value[0].value)+parseFloat(value[1].value))+ '</br>';
                }
                return tips;
            };
            var chartParams={isStack:true,legendPosition:'bottom','isHorizontal':false,barColor:barColor,gridBottom:20,formatterFunc:formatterFunc};
            barChart($("#"+tabId+" #mrScoreEchart"), lines, echartData, "首页各检查项目得分情况", '',chartParams) ;

            // 首页得分分项统计
            var columns=[
                {"data": "ddesc"},
                {"data": "fullScore"},
                {"data": "score"},
                {"data": "minusScore"}
            ];
            var th = "",td = "";
            for(var ptc in partClass){
            	th += " <th colspan=\"2\" style=\"text-align:center\">"+partClass[ptc]+"</th>" ;
            	td += " <th>满分</th><th>扣分</th>";
            	columns.push({"data": "fullScore"+ptc});
            	columns.push({"data": "minusScore"+ptc});
            }
            // 得分明细表格
            $("#"+tabId+" #mrScoreTable").html("<thead>"+
    				" <tr>"+
    				" <th rowspan=\"2\" style=\"text-align:center\">检查项目</th>"+
    				" <th colspan=\"3\" style=\"text-align:center\">平均分数</th>"+
    				th+
    				" </tr><tr>"+
    				" <th>满分</th>"+
    				" <th>得分</th>"+
    				" <th>扣分</th>"+
    				td+
    				" </tr>"+
    				" </thead>");
            var paramsDataTables={searching:false,paging:false,info:false,ordering:true,scrollX:true,autoWidth:false,tableTitle:"首页各检查项目分值统计表"};
            $("#"+tabId+" #mrScoreTable").dataTableBasic(columns,tableData,paramsDataTables);
        })
    }


}

/**
 * @Description: ajax 请求
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 21:54 
 */
function ajaxMr(url,param,func) {
    return $.post(contextPath+"/"+url+".dhc",param).done(function(result){
    	//$.isFunction()函数用于判断指定参数是否是一个函数。jQuery 1.3之后的版本例如在 Internet Explorer 中，
    	//由浏览器提供的函数alert()，以及 DOM 元素方法(比如 getAttribute())将不被认为是函数。
        if (_.isFunction(func)) {
            func(result) ;
        }
    })
}


/**
 * @Description: 数字格式化
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 12:51 
 */
function formatNumMr(num,decimal) {
    if(!num || isNaN(num)) {
        if(isNaN(decimal)) {
            return decimal ;
        } else {
            return formatNumber("0",decimal) ;
        }
    }
    return formatNumber(num,decimal)
}

/**
 * @Description: 除法运算
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/8 20:01 
 */
function division(a,b) {
    if(isNumberMr(a) && isNumberMr(b) && Number(b)!= 0){
        return a/b ;
    } else {
        return "" ;
    }
}


/**
 * @Description: 判斷是否是數字
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/8 19:41
 */
function isNumberMr(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

/**
 * @Description: 根据表格违规项数据绘图
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 22:00
 */
function drawItemsEchartByTableData(iDisplayStart,iDisplayLength,aiDisplay,aoData,echartsContainer,keyMap){

    var eChartsData = [];
    if(iDisplayLength < 0){
        iDisplayLength = aoData.length;
    }
    var dataX = [] ; // 规则相
    var dataYL = [] ; // 违规病案占比
    for (var i=0; i<iDisplayLength; i++){
        var aDatanum = aiDisplay[iDisplayStart+i];
        if(typeof(aoData[aDatanum]) != "undefined"){
            var aData = aoData[aDatanum]._aData;
            dataX.push( aData["ruleName"]) ;
            dataYL.push(aData["violationCaseRatio"]) ;
        }
    }

    var legend=['违规病案占比(%)'];
    var xAxis = [{type : 'category',axisTick : {show: false},data : dataX,silent: false, triggerEvent:true}]; // 规则项
    xAxis[0].axisLabel = {
        interval:0,
        rotate:-20,
        margin: 5,
        fontsize:6 ,
        textStyle:{
            // color:'#ddd',
                align: 'top'

        },
        formatter: function (name) {
            return echarts.format.truncateText(name, 70, '14px Microsoft Yahei', '…');
        },
        tooltip: {
            show: true
        }
    } ;
    var yAxis = [{type : 'value',name : '违规病案占比(%)',axisLabel : {formatter: '{value} %'}}];
    var series = [
        {name:'违规病案占比(%)',type:'bar',data:dataYL}, // 病案占比
    ];
    var chartParams={};
    barLineMixChartBasic(echartsContainer, legend,series,xAxis,yAxis,'违规项分布','',chartParams);

}

/**
 * @Description:根据表格违规科室数据绘图
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 9:29
 */
function drawDepsEchartByTableData(iDisplayStart,iDisplayLength,aiDisplay,aoData,echartsContainer,keyMap){
    var valueCode = keyMap["valueCode"] ;
    var eChartsData = [];
    if(iDisplayLength < 0){
        iDisplayLength = aoData.length;
    }
    if(iDisplayStart < 0){
    	iDisplayStart = 0;
    }
    var dataX = [] ; // 规则相
    var dataYL = [] ; // 违规病案占比
    var dataYR = [] ; // 得分
//    for (var i=iDisplayLength-1; i>=0; i--){
    for (var i=0; i<iDisplayLength; i++){
        var aDatanum = aiDisplay[iDisplayStart+i];
        if(typeof(aoData[aDatanum]) != "undefined"){
            var aData = aoData[aDatanum]._aData;
            dataX.push(aData["ddesc"]) ;
            dataYL.push(aData["violationCaseRatio"]) ;
            dataYR.push(aData["avgScore"]) ;
        }
    }

    var legend=['违规病案占比(%)',"得分"];
    var xAxis = [{type : 'category',data : dataX}]; // 规则项
    xAxis[0].axisLabel = {
        interval:0,
            rotate:-20,
            margin: 10,
            textStyle:{
                align: 'top'

        },
    } ;
    var yAxis = [{type : 'value',name : '违规病案占比(%)'} // ,axisLabel : {formatter: '{value} %'}
        , {type : 'value',name : '得分',splitLine:{show:false}}
    ];
    var series = [
        {name:'违规病案占比(%)',type:'bar',data:dataYL}, // 病案占比
        {name:'得分',type:'line',yAxisIndex: 1,data:dataYR} // 得分
    ];
    var chartParams={};
    barLineMixChartBasic(echartsContainer, legend,series,xAxis,yAxis,'违规项分布','',chartParams);

}

/**
 * @Description: 项目项分布链接
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/6 13:41
 */
function violationItemsA(code,currentObj) {
    var ddesc = $(currentObj).attr("ddesc") ;
    $.post(contextPath + "/pages/common/top-dialog.jsp").done(function(data) {
        var dialog  = $(data);
        dialog.find(".modal-dialog").attr("id","mrQCItemsDialog");
        dialog.find(".modal-title").html(ddesc+"-"+"违规分布");
        dialog.modal({
            keyboard: false,
            backdrop:"static"
        }).on({
            "hidden.bs.modal" : function(){
                $(this).remove();
            },
            "shown.bs.modal" : function(){
                dialog.find(".echartscq").html("<div id=\"violationItemsEchart\" class=\"col-md-6\" style=\"height:300px;\"></div>" +
                    "                        <div class=\"col-md-6\" style=\"height:300px;\">" +
                    "                            <table id=\"violationItemsTable\" style=\"white-space:nowrap\" cellspacing=\"0\" width=\"100%\"></table>" +
                    "                        </div>");
                var condition  = {} ;
                condition[$(currentObj).attr("name")] = code ;
                condition["monitorType"] = $(currentObj).attr("monitorType") ;
                condition.linkA = true ;
                drawViolationItems(condition,dialog.find("#violationItemsTable"),dialog.find("#violationItemsEchart")) ;
            }
        });
    });
}

/**
 * @Description: 项目违规科室分布链接
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/12 22:10 
 */
function violationDepA(ruleCode,violationCaseCnt,currentObj) {
    var monitorType = $(currentObj).attr("monitorType") ;
    var monitorName = titleMrQuality[monitorType].desc ;
    var ddesc = $(currentObj).attr("ddesc") ;
    $.post(contextPath + "/pages/common/top-dialog.jsp").done(function(data) {
        var dialog  = $(data);
        dialog.find(".modal-body").css("padding","20px 10px");
        dialog.find("#echartcq4").css("width","100%");
        dialog.find(".modal-dialog").attr("id","mrQCDepsDialog");
        dialog.find(".modal-title").html(ddesc+"-违规"+monitorName+"分布");
        // dialog.find(".echartscq").css({"height":"100%","overflow":"hidden"})
        dialog.modal({
            keyboard: false,
            backdrop:"static"
        }).on({
            "hidden.bs.modal" : function(){
                $(this).remove();
            },
            "shown.bs.modal" : function(){
                if(monitorType!="doctor"){
                    dialog.find("#echartcq4").html("<div id=\"violationDepsEchart\" class=\"col-md-6\" style=\"height:320px;\"></div>" +
                        "                        <div class=\"col-md-6\">" +
                        "                            <table id=\"violationDepsTable\" class=\"display\" style=\"white-space:nowrap\" cellspacing=\"0\" width=\"100%\"></table>" +
                        "                        </div>");
//                    dialog.find(".col-md-6").eq(1).css('padding-left','0px').css('padding-right','10px');
                    var condition  = {} ;
                    condition.ruleCode = ruleCode ; // 规则编码
                    condition.linkA = true ; // 从链接跳过
                    condition.violationCaseCnt = violationCaseCnt ;
                    condition.monitorType = monitorType ;
                    drawViolationDeps(condition,dialog.find("#violationDepsTable"),dialog.find("#violationDepsEchart")) ;                   
                    
                } else {
                    var id="violateDiag" ;
                    dialog.find("#echartcq4").html("<div class=\"col-md-12 column padding10\" id=\"violateDiag\">" +
                        "                    <div class=\"infocq \">" +
                        "                        <div class=\"tabconti blue-bg\">" +
                        "                            <span class=\"title28 mTypeName\">医师</span>违规" +
                        "                        </div>" +
                        "" +
                        "<ul class=\"nav nav-tabs tabconulcq\" role=\"tablist\">" +
                        "</ul>" +
                        "<div class=\"clearfix\"></div>" +
                        "<div class=\"tab-content\"></div>");
                    var condition  = {} ;
                    condition.ruleCode = ruleCode ; // 规则编码
                    condition.linkA = true ; // 从链接跳过
                    condition.violationCaseCnt = violationCaseCnt ;
                    drawViolationDoctor(id,dialog,condition) ;
                }
            }
        });
    });
}

/**
 * @Description: 判断是否是医师层
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/15 14:44 
 */
function isDoctorMonitorType(monitorType) {
    if($.inArray(monitorType,docTypeArray)>-1) {
        return true ;
    }
    return false ;
}

/**
 * @Description: 违规项模块
 * @param  tableObj 表格对象
 * @param  result  ajax返回结果
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/10 21:10
 */
function drawViolationItems(condition,tableObj,echartObj) {
    var param = drgUI.setAjaxData(tabId) ;
    // 只复制自己的属性覆盖到目标对象(underscore-JavaScript实用库)
    _.extendOwn(param, condition) ;
    var monitorType = param.monitorType ;
    var monitorName = titleMrQuality[monitorType].desc ;
    if (isDoctorMonitorType(monitorType)) {
        monitorName = titleMrQuality["doctor"].desc ;
    }
    ajaxMr("medicalRecordQuality/violationItems",param,function (result) {
        if(result == null || result.data == undefined){
            result = [] ;
        } else {
            result = result.data ;
        }
        for (var o in result) {
            result[o].violationCaseRatio = formatNumber(division(result[o].violationCaseCnt,result[o].totalMedicalRecord)*100,2) ;
        }
        // 表格数据
        var columns=[
            {"data": "","title":"序号",
                "render":function(data,type,full,meta){
                    return meta.row+1 ;
                }
            },
            {"data": "ruleName","title":"规则名称" ,"render":function(data,type,full,meta){
            		var showInfo = '<div  class="drgtips" id="tp'+meta.row+'" tips="'+full.ruleIntroduction+'"> ';
            		showInfo += linefeedText(data,10)+'</div>';
            		return showInfo;
                }
            },
            {"data": "scoreName","title":"所属分项" },
            {"data": "weightName","title":"所属类别" },
            {"data": "violationCaseCntT","title":"违规<br>病案数",
                "render": function(obj, type, full) {
                    if (condition && condition.linkA) {
                        return full.violationCaseCnt ;
                    }
                    return "<a href=\"javascript:void(0);\" monitorType=\""+monitorType+"\" name=\"ruleCode\" ddesc=\""+full.ruleName+"\" onclick=\"loadQCCaseDtl('"+full.ruleCode+"',this) \">"+full.violationCaseCnt+"</a>" ;
                }
            },
            {"data": "violationCaseRatio","title":"违规<br>病案占比(%)"},
            {"data": "","title":"操作",
                "render": function(obj, type, full) {
                    return "<a monitorType=\""+monitorType+"\" ddesc=\""+full.ruleName+"\" href=\"javascript:void(0);\" onclick=\"violationDepA('"+full.ruleCode+"',"+full.violationCaseCnt+",this)\">"+monitorName+"分布</a>" ;
                }
            }
        ];

        if ((condition && condition.linkA  || isDoctorMonitorType(paramTabPage[tabId].monitorType))) {
            columns.pop() ;
        }
        var drawCallback  = function (oSettings) {
            var keyMap = {"ccode":"ruleCode","ddesc":"ruleName","valueCode":"violationCaseRatio"} ;
            drawItemsEchartByTableData(oSettings._iDisplayStart,oSettings._iDisplayLength,oSettings.aiDisplay,oSettings.aoData,echartObj,keyMap);
            //调整一下搜索框的宽度，防止 表格信息行和搜索框宽度不合适而显示成2行
            echartObj.next().find(".dataTables_filter").css('width','40%').end().find('input').css('width','80%');
        }
        var paramsDataTables={searching:true,info:false,ordering:true,scrollX:true,scrollY:'200px',autoWidth:false,tableTitle:"违反的规则统计"};
        paramsDataTables.drawCallback = drawCallback ;
        tableObj.dataTableBasic(columns,result,paramsDataTables);
    });
}


/**
 * @Description:
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/13 16:39 
 */
function loadQCCaseDtl(code,currentObj) {
    var param = drgUI.setAjaxData(tabId) ;
    param[$(currentObj).attr("name")] = code ;
    param["monitorType"] = $(currentObj).attr("monitorType") ;
    param["ddesc"] = $(currentObj).attr("ddesc") ;
    var pageId = code+param["ruleCode"]+"mrQualityCaseDtl" ;
    openTab('/pages/medicalRecordQuality/mrQualityCaseDtl.jsp',param["ddesc"]+'|病例明细', pageId,pageId,param);
}

/**
 * @Description: 违规科室模块
 * @param
 * @return
 * @throws
 * @author chenhanlin
 * @date 2018/8/13 9:00
 */
function drawViolationDeps(condition,tableObj,echartObj) {
    var param = drgUI.setAjaxData(tabId) ;
    // 只复制自己的属性覆盖到目标对象(underscore-JavaScript实用库)
    _.extendOwn(param, condition) ;
    // 修改标题
    var monitorName = "" ;
    if(isDoctorMonitorType(param.monitorType)){
        monitorName = titleMrQuality["doctor"].desc ;
    } else {
        monitorName = titleMrQuality[param.monitorType].desc ;
    }
    $("#"+tabId+" .mTypeName").text(monitorName) ;
    ajaxMr("medicalRecordQuality/violationDeps",param,function (result) {
        if (result == null || result.data == undefined) {
            result = [];
        } else {
            result = result.data;
        }
        var violationCaseCnt = 1 ;
        // 违规病例数
        // condition里的violationCaseCnt，是点击科室/医师分布是传的参数
        if(condition && condition.violationCaseCnt) {
            violationCaseCnt = condition.violationCaseCnt ;
        } else if (result.length>0){
            violationCaseCnt = result[0].totalMedicalRecord ;
        }
        for (var o in result) {
            result[o].violationCaseRatio = formatNumber(division(result[o].violationCaseCnt, violationCaseCnt) * 100, 2);
            result[o].poorRatio = formatNumber(division(result[o].poor, violationCaseCnt) * 100, 2);
        }
        var name = findConditionalAttributeByMonitorType(param.monitorType) ;
        var columns=[
            {"data": "","title":"序号",
                "render":function(data,type,full,meta){
                    return meta.row+1 ;
                }
            },
            {"data": "ddescT","title":monitorName+"名称",
                "render": function(obj, type, full) {
                    // a 链接过来的，不再跳转。不是a链接过来的
                    if ((condition && condition.linkA)) {
                        return full["ddesc"] ;
                    } else {
                        return "<a monitorType=\""+param.monitorType+"\"  href=\"javascript:void(0);\" onclick=\"drillNextLayer('"+full.ccode+"','"+full["ddesc"]+"',this)\">"+full["ddesc"]+"</a>" ;
                    }
                }
            },
            {"data": "avgScore","title":"得分"},
            {"data": "violationCaseCntT","title":"违规病案数",
                "render": function(obj, type, full) {
                    if (condition && condition.linkA) {
                        return full.violationCaseCnt ;
                    }
                    return "<a href=\"javascript:void(0);\" monitorType=\""+param.monitorType+"\"  name=\""+name+"\" ddesc=\""+full.ddesc+"\" onclick=\"loadQCCaseDtl('"+full.ccode+"',this) \">"+full.violationCaseCnt+"</a>" ;
                }
            },
            {"data": "violationCaseRatio","title":"违规病案<br>占比(%)"},
            {"data": "","title":"操作",
                "render": function(obj, type, full) {
                   return "<a monitorType=\""+param.monitorType+"\" ddesc=\""+full.ddesc+"\" name=\""+name+"\"  href=\"javascript:void(0);\" onclick=\"violationItemsA('"+full.ccode+"',this)\">违规分布</a>" ;
                }
            }
        ];
        //  a 链接过来的不再钻取 或者 页面首次加载的时候 科室的操作列不用显示
        if ( (condition && condition.linkA) || (condition && condition.monitorType == 'dep') ) {
            columns.pop() ;
        }
        var drawCallback  = function (oSettings) {
            var keyMap = {"ccode":"ccode","ddesc":"ddesc","valueCode":"violationCaseRatio"} ;
            drawDepsEchartByTableData(oSettings._iDisplayStart,oSettings._iDisplayLength,oSettings.aiDisplay,oSettings.aoData,echartObj,keyMap);
            //调整一下搜索框的宽度，防止 表格信息行和搜索框宽度不合适而显示成2行
            echartObj.next().find(".dataTables_filter").css('width','40%').end().find('input').css('width','80%');
        }
        var paramsDataTables={searching:true,info:false,ordering:true,scrollX:true,scrollY:'200px',autoWidth:false,tableTitle:"违反的规则统计"};
        paramsDataTables.drawCallback = drawCallback ;
        tableObj.dataTableBasic(columns,result,paramsDataTables);
    });
}

/**
 * @Description: 下一层级钻取
 * @param  
 * @return  
 * @throws
 * @author chenhanlin
 * @date 2018/8/12 22:14 
 */
function drillNextLayer(code,desc,thisObj) {
    var param = drgUI.setAjaxData(tabId) ;
    // var titleName = desc ;
    param.monitorType = $(thisObj).attr("monitorType") ;
    if($.inArray(param.monitorType,docTypeArray)){
        param.doctorType = true ;
    }
    // 参数的属性名
    var attr = findConditionalAttributeByMonitorType(param.monitorType) ;
    param[attr] = code ;
    param.previous = paramTabPage[tabId].monitorType ;
    pageId = code+param.monitorType+"mrQualityHomePage";
    openTab('/pages/medicalRecordQuality/mrQualityHomePage.jsp',desc+'|首页质量', pageId,pageId,param);
}

